namespace Digitalmes.Application.Sys.Roles.Commands;

/// <summary>
/// 更新角色命令。
/// </summary>
public record UpdateRoleCommand(long Id, SysRoleDto Role) : IRequest<IResult<bool>>;

internal sealed class UpdateRoleCommandHandler(IRepository<SysRole> repo) : IRequestHandler<UpdateRoleCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
    {
        // 检查账号名是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Role.Code && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("角色编号已存在");
        }

        var role= await repo.GetByIdAsync(request.Id, cancellationToken);
        if (role == null)
        {
            return Result.Failure("未找到要更新的角色");
        }

        role.Name = request.Role.Name;
        role.Order = request.Role.Order;
        role.Remark = request.Role.Remark;
        role.Status = request.Role.Status;

        var ok = await repo.UpdateAsync(role, m => new
        {
            m.Name,
            m.Order,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
